#!/bin/bash

# 脚本名称: mysql-to-md.sh

# 功能: 将 MySQL 查询结果导出为 Markdown 格式

# MySQL 连接信息

DB_USER="your_username"
DB_PASS="your_password"
DB_NAME="your_database"
DB_HOST="localhost"
TABLE_NAME="reader"
OUTPUT_FILE="mysql_query_result.md"

# 获取表的列名

COLUMNS=$(mysql -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME -e "SHOW COLUMNS FROM $TABLE_NAME;" | awk 'NR>1 {print $1}')

# 创建 Markdown 表头

echo "# $TABLE_NAME 表查询结果" > $OUTPUT_FILE
echo "" >> $OUTPUT_FILE

# 添加表头行

HEADER="|"
SEPARATOR="|"
for col in $COLUMNS; do
    HEADER="$HEADER $col |"
    SEPARATOR="$SEPARATOR --- |"
done

echo "$HEADER" >> $OUTPUT_FILE
echo "$SEPARATOR" >> $OUTPUT_FILE

# 查询数据并格式化为 Markdown

mysql -h $DB_HOST -u $DB_USER -p$DB_PASS $DB_NAME -e "SELECT * FROM $TABLE_NAME;" | tail -n +2 | while read -r line; do
    ROW="|"
    for val in $line; do
        ROW="$ROW $val |"
    done
    echo "$ROW" >> $OUTPUT_FILE
done

echo "" >> $OUTPUT_FILE
echo "查询完成，结果已保存到 $OUTPUT_FILE"
